package com.techgene.kanban.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

import com.techgene.kanban.dao.LoginDao;
import com.techgene.kanban.domain.User;
import com.techgene.kanban.exception.KBDaoException;
import com.techgene.kanban.util.AppConstants;

@Component
public class LoginDaoImpl implements LoginDao {

	private Logger logger = LoggerFactory.getLogger(LoginDaoImpl.class);

	@Autowired
	DataSource dataSource;




	/**
	 * find user by user name
	 * 
	 * @param user name
	 * @param password
	 * @throws KBDaoException
	 */
	public User findUserByUsername(String username, String password)
			throws KBDaoException {
		logger.debug(">> findUserByUsername [username = {}, password ={}] ",username, password);

		User user = new User();
		try{

			String sql = "select username, password, role, email from tbl_user where username = ? and password = ?";

			JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
			user = jdbcTemplate.query(sql, new Object[] { username, password },
					new ResultSetExtractor<User>() {
				public User extractData(ResultSet rs) throws SQLException,DataAccessException {
					User user = new User();						
					while (rs.next()) {
						user.setUsername(rs.getString("username"));
						user.setPassword(rs.getString("password"));
						user.setRole(rs.getString("role"));
						user.setEmail(rs.getString("email"));
					}
					return user;
				}
			});


		}catch(Exception e){ 

			/* for any other errors */			
			throw new KBDaoException(AppConstants.ERROR.DAO_UNKNOWN_ERROR_VALIDATING_USER_DETAILS.code,
					AppConstants.ERROR.DAO_UNKNOWN_ERROR_VALIDATING_USER_DETAILS.msg, e);

		}catch(Throwable e){		

			throw new KBDaoException(AppConstants.ERROR.DAO_UNKNOWN_ERROR_VALIDATING_USER_DETAILS.code,
					AppConstants.ERROR.DAO_UNKNOWN_ERROR_VALIDATING_USER_DETAILS.msg, e);
		}

		logger.debug("<< findUserByUsername [user = {}]", user);

		return user;
	}

}
